<template>
  <div>
    <a-form-model ref="di_rel_dept_correctForm" :model="di_user" >
      <a-form-model-item
        v-if="!isView"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        label="关联用户电话"
        prop="mobile"
        has-feedback
        required>
        <a-row>
          <a-col :span="18" style="padding-right: 16px;">
            <a-input
              allow-clear
              v-model="di_user.mobile"
              :maxLength="50"
              @change = "mobileChange()"
              placeholder="请输入关联用户电话" />
          </a-col>
          <a-col :span="6" style="padding-left: 1px;">
            <a-button
              icon="search"
              type="primary"
              @click="searchUser(di_user.id,di_user.mobile)"
              v-if="!isView">查询
            </a-button>
          </a-col>
        </a-row>
      </a-form-model-item>
      <div v-if="this.showTable">
      <a-form-model-item
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        label="人员信息"
      >
        姓名：{{this.userList[0].userName}}
        <a-divider type="vertical"></a-divider> 性别：{{this.userList[0].sexText}}
        <a-divider type="vertical"></a-divider> 级别：{{this.userList[0].careerRankText}}
      </a-form-model-item>
      </div>
      <a-form-model-item>
        <div style="text-align: center">
          <a-input type="hidden" :disabled="true" v-model="di_user.id" />
          <a-button :style="{ marginRight: '8px' }" icon="close" @click="onClose"> 关闭</a-button>
          <a-button :style="{ marginRight: '8px' }" icon="reload" @click="resetForm" v-if="!isView"> 重置</a-button>
          <a-button type="primary" @click="onSubmit" icon="save" :loading="loading" v-if="!isView"> 保存</a-button>
        </div>
      </a-form-model-item>
    </a-form-model>
  </div>
</template>
<script>
/* eslint-disable */
import {
  getDeptAndUser,
  queryUserByMobile,
  updataContactuser
} from '@/api/ding/di_rel_dept_correct'

export default {
  data () {
    return {
      di_dept_id: '',// 机构id
      labelCol: { span: 6 }, // label宽
      wrapperCol: { span: 18 }, // 组件宽
      loading: false, //按钮显示
      isView: false, //是否查看
      showTable: false,
      di_user: {
        id: '',
        orgname: '',
        fid: '',
        adid: '',
        mobile: '',
        contactuser: '',
        orgtype: ''
      }, //角色信息
      userList: [],
      ucolumns:[
        {
          title: '姓名',
          dataIndex: 'userName',
          key: 'userName',
          align: 'left',
          width: 150
        },
        {
          title: '电话',
          dataIndex: 'mobile',
          key: 'mobile',
          align: 'left',
          width: 150
        },
        {
          title: '性别',
          dataIndex: 'sexText',
          key: 'sexText',
          align: 'left',
          width: 100
        },
        {
          title: '岗位级别',
          dataIndex: 'careerRankText',
          key: 'careerRankText',
          align: 'left',
          width: 250
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '120px',
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      rules: {
        mobile: [{ required: true, validator: this.checkMobile }],
      },
    }
  },
  created () {
  },
  methods: {
    checkMobile (rule, value, callback) {
      if (!value) {
        callback(new Error('请输入联系号码'))
      }
      if (value && !/^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/.test(value)) {
        callback(new Error('请输入正确的联系号码'))
      }
      callback()
    },
    /**
     * 调用父组件的方法收起抽屉
     */
    onClose () {
      this.$emit('close')
    },
    /**
     * 提供给父组件调用
     * 点击新增进入时重置表单数据
     */
    resetDi_rel_dept_correct () {
      this.isView = false
      this.resetForm()
    },

    searchUser (id, mobile) {
      queryUserByMobile(mobile).then((res) => {
        if (res.code == 0 ) {
          this.showTable = true
          this.userList = []
          this.userList = res.data
          if(!res.data || res.data.length<=0){
            this.$message.error("未查询到用户")
          }
        }
      })
    },
    handleEdit (record) {
      this.di_user.mobile = record.mobile
      this.di_user.contactuser = record.id
      this.showTable = false
    },
    /**
     * 提供给父组件调用
     * 查询用户信息
     */
    findDeptAndUserById (id, isView) {
      this.isView = isView
      //this.resetForm()

      getDeptAndUser(id).then((res) => {
        if (res.code == 0) {
          this.di_dept_id = id
          if(!res.data){
            console.log("编辑人员",this.di_user)
            this.showTable = false
          }else {
            this.di_user = res.data
            this.userList = []
            this.userList.push(res.data)
            this.showTable = true
          }
        }
      })
    },
    /**
     * 重置表单
     */
    resetForm () {
      this.$refs.di_rel_dept_correctForm.resetFields()
    },
    /**
     * 提交表单
     */
    async onSubmit () {
      let res = await queryUserByMobile(this.di_user.mobile)
      if (res.code != 0 || !res.data || res.data.length <= 0) {
        this.$message.error('当前号码不属于赣政通用户')
        return
      }
      const user = res.data[0]
      this.$refs.di_rel_dept_correctForm.validate((valid) => {
        this.loading = true
        if (valid) {
          delete this.di_user.primaryKey
          const savem = this.$message.loading('数据正在保存中...', 0)
          updataContactuser({
            id: this.di_dept_id,
            contactuser: user.id
          }).then((res) => {
            if (res.code !== 0) {
              setTimeout(savem, 0)
              this.$message.error('关联用户修改失败')
              this.loading = false
            } else {
              setTimeout(savem, 0)
              this.$message.success('保存成功')
              this.$emit('reloadList')
              this.$emit('close')
              this.loading = false
            }
          })
        } else {
          this.loading = false
          // 加延时器的目的是为了vue实例更新未完成，我们可能获取DOM失败的问题
          // 利用原生js的方式，获取所有失败的类名，获得一个数组，取第一个元素获取焦点
          setTimeout(() => {
            const isError = document.getElementsByClassName('has-error')
            const input = isError[0].querySelector('input')
            //console.log(input)
            if (input !== null && input !== 'undefind' && input !== '') {
              isError[0].querySelector('input').focus()
                ? isError[0].querySelector('input').focus()
                : isError[0].querySelector('input').click()
            } else {
              isError[0].querySelector('textarea').focus()
            }
          }, 10)
          return false
        }
      })
    },
    mobileChange(){
      this.showTable = false
      if(this.di_user.mobile && this.di_user.mobile.length==11){
        this.searchUser(this.di_user.id,this.di_user.mobile)
      }
    },
  }
}
</script>
<style lang="less" src="@/style/base.less">
</style>